package com.example.zhu.controller;

import com.example.zhu.dto.R;
import com.example.zhu.dto.Student;
import com.example.zhu.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/common")
@Slf4j
public class imgController {
    @Value("${img.path}")
    private String basePath;
    @Autowired
    private StudentService studentservice;

    @Transactional
    @PostMapping("/img/{id}")
    //MultipartFile 译为多部分的文件
    public R<String> upload(@RequestBody MultipartFile img, @PathVariable("id") String id) {
        //原始文件名
        String originalFilename = img.getOriginalFilename();
        //获取文件后缀名，
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = id + suffix;
        //创建一个目录对象
        // 获取当前项目所在的目录
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            img.transferTo(new File(basePath + fileName));
            Student student = new Student();
            student.setId(id);
            student.setImg(fileName);
            studentservice.updateData(student);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String id, HttpServletResponse response) throws IOException {
        try {
            Student student = studentservice.getById(id);
            if (student != null) {
                if (student.getImg() != null) {
                    String fileImg = basePath + "/" + student.getImg();
                    FileInputStream fileInputStream = new FileInputStream(fileImg);
                    ServletOutputStream outputStream = response.getOutputStream();
                    response.setContentType("image/jpeg");
                    int len = 0;
                    //注意别写成大写
                    byte[] bytes = new byte[1024];
                    while ((len = fileInputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                        outputStream.flush();
                    }
                    //关闭资源
                    outputStream.close();
                    fileInputStream.close();
                    return;
                }
                response.sendRedirect("/find.html");
                return;
            }
            response.sendRedirect("/find.html");
            return;
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("/find.html");
            return;
        }
    }
}